package cn.szabadsag.hrm.service.impl;

import cn.szabadsag.hrm.client.AuthServiceClient;
import cn.szabadsag.hrm.domain.LoginUser;
import cn.szabadsag.hrm.domain.VipBase;
import cn.szabadsag.hrm.domain.VipUser;
import cn.szabadsag.hrm.dto.ChangePasswordParamsDTO;
import cn.szabadsag.hrm.dto.LoginUserDto;
import cn.szabadsag.hrm.dto.SmsCodeLogDTO;
import cn.szabadsag.hrm.dto.UserRegisterParamsDTO;
import cn.szabadsag.hrm.exception.Assert;
import cn.szabadsag.hrm.exception.BusinessException;
import cn.szabadsag.hrm.mapper.VipUserMapper;
import cn.szabadsag.hrm.service.IVipBaseService;
import cn.szabadsag.hrm.service.IVipUserService;
import cn.szabadsag.hrm.util.AjaxResult;
import cn.szabadsag.hrm.util.BitStatesUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author yangcong
 * @since 2022-04-13
 */
@Service
public class VipUserServiceImpl extends ServiceImpl<VipUserMapper, VipUser> implements IVipUserService {

    @Autowired
    private IVipBaseService vipBaseService;

    @Autowired
    private AuthServiceClient authServiceClient;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 用户注册
     * @param dto
     */
    @Override
    @GlobalTransactional
    public void userRegister(UserRegisterParamsDTO dto) {
        //  1.参数判断 BeanValidation
        Assert.assertPhone(dto.getMobile(),"无效的手机号！");
        //  2.条件判断(手机号码{redis}，手机号去重{mysql数据库})
        String smsCodeKey = "sms:" + dto.getMobile();
        SmsCodeLogDTO smsCodeLogDTO = (SmsCodeLogDTO)redisTemplate.opsForValue().get(smsCodeKey);
        Assert.assertNotNull(smsCodeLogDTO,"无效的验证码或验证码已过期!");
        //if (smsCodeLogDTO.getSmsCode() != dto.getSmsCode()){//字符串之间不能直接使用!=作比较
        if (!smsCodeLogDTO.getSmsCode().equals(dto.getSmsCode())){
            throw new BusinessException("手机验证码错误！");
        }
        //  3.手机号查重
        VipUser vpUserFromDB = selectOne(new EntityWrapper<VipUser>().eq("phone", dto.getMobile()));
        Assert.assertNull(vpUserFromDB,"手机号已经被注册！");

        //  4.保存t_login_user
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(dto.getMobile());
        loginUser.setPassword(dto.getPassword());
        loginUser.setType(LoginUser.USER_TYPE_WEBSITE);
        AjaxResult ajaxResult = authServiceClient.add(new LoginUserDto(loginUser, null));
        Assert.assertTrue(ajaxResult.isSuccess(),"登录信息保存失败");
        Assert.assertNotNull(ajaxResult.getResultObj(),"登录信息保存失败");
        Long loginId = Long.valueOf(ajaxResult.getResultObj().toString());

        //  5.保存t_vip_user,设置loginId
        VipUser vipUser = new VipUser();
        vipUser.setLoginId(loginId);
        vipUser.setPhone(dto.getMobile());
        vipUser.setNickName(dto.getMobile());
        vipUser.setCreateTime(new Date().getTime());
        //  注册成功
        long bitState = BitStatesUtils.addState(0L, BitStatesUtils.OP_REGISTED);
        //  账号激活
        bitState = BitStatesUtils.addState(bitState, BitStatesUtils.OP_ACTIVED);
        //  手机认证
        bitState = BitStatesUtils.addState(bitState, BitStatesUtils.OP_AUTHED_PHONE);
        vipUser.setBitState(bitState);
        insert(vipUser);

        //  6.保存t_vip_base
        VipBase vipBase = new VipBase();
        //  注册渠道
        vipBase.setRegChannel(dto.getRegChannel());
        vipBase.setCreateTime(vipUser.getCreateTime());
        vipBase.setSsoId(vipUser.getId());
        vipBase.setRegTime(vipUser.getCreateTime());
        vipBaseService.insert(vipBase);
    }

    /**
     * 用户更改密码
     * @param dto
     */
    @Override
    public void changePassword(ChangePasswordParamsDTO dto) {
        //  1.参数判断、校验
        Assert.assertPhone(dto.getMobile(),"无效的手机号！");
        //  2.条件判断
        /*String smsCodeKey = "sms:" + dto.getMobile();
        SmsCodeLogDTO smsCodeLogDTO = (SmsCodeLogDTO)redisTemplate.opsForValue().get(smsCodeKey);
        Assert.assertNotNull(smsCodeLogDTO,"无效的验证码或验证码已过期!");
        if (!smsCodeLogDTO.getSmsCode().equals(dto.getSmsCode())){
            throw new BusinessException("手机验证码错误！");
        }*/
        //  判断旧密码是否正确
        VipUser vpUserFromDB = selectOne(new EntityWrapper<VipUser>().eq("phone", dto.getMobile()));
        Assert.assertNotNull(vpUserFromDB,"用户不存在！");
        if (!vpUserFromDB.getPassword().equals(dto.getOld_password())){
            throw new BusinessException("密码错误！");
        }
        //  更改t_login_user表
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(dto.getMobile());
        loginUser.setPassword(dto.getNew_password());
        AjaxResult ajaxResult = authServiceClient.uptByUsername(loginUser);
        Assert.assertTrue(ajaxResult.isSuccess(),"密码更改失败!");
        //  更改t_vip_user表
        vpUserFromDB.setPassword(dto.getNew_password());
        updateById(vpUserFromDB);

    }









}
